package com.yhy.common.core.utils;

import cn.hutool.core.codec.Base64;
import cn.hutool.json.JSONUtil;
import com.yhy.common.core.constant.SecurityConstants;
import com.yhy.common.core.exception.BizException;
import com.yhy.common.core.model.ContextUser;
import com.yhy.common.core.result.ResultEnum;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

@Slf4j
@UtilityClass
public class ContextUtil {

    public ContextUser getUser() {
        ContextUser contextUser;
        HttpServletRequest request = WebUtils.getRequest();
        String user = request.getHeader(SecurityConstants.DETAILS_USER);
        Optional.ofNullable(user).orElseThrow(() -> new BizException(ResultEnum.FAILED_PARSE_USER_INFORMATION));
        try {
            contextUser = JSONUtil.toBean(JSONUtil.toJsonStr(Base64.decodeStr(user)), ContextUser.class);
        } catch (Exception e) {
            log.error(ResultEnum.FAILED_PARSE_USER_INFORMATION.getMsg(), e);
            throw new BizException(ResultEnum.FAILED_PARSE_USER_INFORMATION);
        }
        return contextUser;
    }

    public Long getUserId() {
        return getUser().getId();
    }

    public String getClientId() {
        return getUser().getClientId();
    }

}
